<template>
  <view class="container">
    <FilterNavbar :searchList="searchList" v-model:queryParam="queryParam" @confirm="onFilterNavbarConfirm">
      <template #center>
        <view class="navbar-title"> 车辆管理 </view>
      </template>
    </FilterNavbar>
    <ve-search-bar placeholder="请输入车牌号/车型名称" @search="searchBarSearch" />
    <ve-tabs :actived="activedTab" :list="dict.operateStatusList" @change="tabsChange"></ve-tabs>
    <scroll-view
      scroll-y
      :scroll-top="scrollTop"
      :scroll-with-animation="true"
      refresher-enabled
      :refresher-triggered="refreshStatus"
      :enable-back-to-top="true"
      @refresherrefresh="resetRefresh(true)"
      @scrolltolower="reachBottom"
    >
      <view class="record-list">
        <block v-for="item in dataSource" :key="item">
          <ManagerItem :manager-item="item" :resetRefresh="resetRefresh" />
        </block>
      </view>
      <!-- 加载结束列表为空时展示 -->
      <ve-empty v-if="dataSource.length == 0 && loadStatus == 'nomore'"></ve-empty>
      <!-- 底部加载状态 -->
      <ve-load-more v-else :status="loadStatus" bgColor="#F7F7F9"></ve-load-more>
    </scroll-view>
    <ve-bottom-box size="mini" v-if="usePermission('svmsapp:car-manage.add')">
      <ve-button type="primary" size="long" @click="navigatorAdd">新增车辆</ve-button>
    </ve-bottom-box>

    <!-- 处置车辆 -->
    <DisposePlate v-model:visible="plate.disposeVisible" :id="plate.id" :source="plate.source" @confirm="onConfirmDispose" />

    <!-- 更换车牌号 -->
    <ReplicePlate v-model:visible="plate.repliceVisible" :id="plate.id" :plateNumber="plate.licenseNo" @confirm="onConfirmReplice" />

    <ve-confirm titleText="提示" v-model="visible" @confirm="onConfirm" @cancel="onCancel">
      {{ prompts }}
    </ve-confirm>

    <ve-confirm titleText="提示" v-model="confirmVisible" cancelText="关闭" :showCancel="false" @confirm="onPCConfirm">
      当前车牌号在归还车辆中已存在，请前往pc端网页版的归还车辆操作再次借入
    </ve-confirm>
  </view>
</template>

<script setup lang="ts">
  import FilterNavbar from '@/components/FilterNavbar'
  import ManagerItem from './components/manager-item.vue'
  import { usePermission } from '@/hooks/usePermission'
  import DisposePlate from './components/dispose-plate.vue'
  import ReplicePlate from './components/replice-plate.vue'

  import { computed, ref, reactive } from 'vue'
  import { usePageDict } from '@/hooks/useDict'
  import useList from '@/hooks/useList'
  import { onLoad, onUnload } from '@dcloudio/uni-app'
  import { changeLicenseNo, disposeCar, checkDisposal, checkLicenseNo, checkReturnCar } from '@/api/asset/car-manager'
  import { getEnterpriseDetail } from '@/api/common'

  const plate = reactive<any>({
    repliceVisible: false,
    disposeVisible: false,
    id: '',
    licenseNo: '',
    source: null,
    modelId: '',
    vin: '',
  })
  // 更换车牌号
  uni.$on('repliceVisibleFn', function (data) {
    console.log(data)
    plate.id = data.id
    plate.licenseNo = data.licenseNo
    plate.source = data.source
    plate.modelId = data.modelId
    plate.vin = data.vin
    if (plate.id) {
      plate.repliceVisible = true
    }
  })
  // 处置
  uni.$on('disposeVisibleFn', function (data) {
    console.log(data)
    plate.id = data.id
    plate.licenseNo = data.licenseNo
    plate.source = data.source
    if (plate.id) {
      plate.disposeVisible = true
    }
  })

  const confirmVisible = ref(false)
  const onChangeLicenseNo = (form: any) => {
    const params = {
      id: plate.id,
      licenseNo: form.licenseNo,
    }
    changeLicenseNo(params).then(() => {
      plate.repliceVisible = false
      setTimeout(() => {
        plate.id = ''
        form.licenseNo = ''
      }, 500)
      resetRefresh()
    })
  }

  const onPCConfirm = () => {
    confirmVisible.value = false
  }

  const onConfirmReplice = async (form: any) => {
    if (plate.source == 2) {
      try {
        const _ = await checkLicenseNo({ licenseNo: form.licenseNo, vin: plate.vin, carInfoId: plate.id })

        const { code, result } = await checkReturnCar({ licenseNo: form.licenseNo, modelId: plate.modelId })
        console.log('checkReturnCar', code, result)
        if (code == '200') {
          if (!result) {
            onChangeLicenseNo(form)
          } else {
            confirmVisible.value = true
          }
        }
      } catch (error) {
        console.log('error', error)
      }
    } else {
      onChangeLicenseNo(form)
    }
  }

  const visible = ref(false)
  const prompts = ref('')
  const formData = ref({})

  /** 处置车辆 */
  const disposeCarHandle = () => {
    disposeCar(formData.value)
      .then(() => {
        console.log('处置车辆成功')
        uni.showToast({
          title: '已处置',
          icon: 'success',
          mask: true,
        })

        plate.disposeVisible = false
        visible.value = false
        plate.id = ''
        resetRefresh()
      })
      .catch((error) => {
        uni.showToast({
          title: error.data.message,
          icon: 'none',
          mask: true,
        })
      })
  }

  const onConfirm = () => {
    disposeCarHandle()
  }
  const onCancel = () => {
    visible.value = false
  }

  const onConfirmDispose = (form: any) => {
    console.log(form)
    formData.value = {
      id: plate.id,
      disposalType: form.disposalType,
      disposalTime: form.disposalTime,
      disposalAmount: form.disposalAmount,
      disposalRemark: form.disposalRemark,
    }

    checkDisposal({ id: plate.id }).then((res: any) => {
      const { prompt } = res.result
      if (prompt) {
        prompts.value = prompt
        visible.value = true
      } else {
        disposeCarHandle()
      }
    })
  }

  const dict = usePageDict('carManagerToListDict', (val: any) => {
    if (val.operateStatusList[0].label === '全部') return
    val.operateStatusList.unshift({ label: '全部', value: '' })
  })

  const queryParam = ref<any>({
    operateStatus: undefined,
    siteId: undefined,
    siteName: undefined,
    pageNumber: 1,
  })

  const { resetRefresh, reachBottom, loadData, scrollTop, loadStatus, refreshStatus, dataSource } = useList(
    '/V5/carInfo/getList',
    queryParam,
  )

  const searchList = computed(() => {
    return [
      {
        prop: 'siteId',
        label: '所属门店',
        type: 'remote-select',
        attrs: {
          label: queryParam.value.siteName,
          type: 'site',
        },
      },
      {
        prop: 'source',
        label: '车辆来源',
        type: 'picker',
        attrs: {
          options: dict.sourceEnumList,
        },
      },
      {
        prop: 'tagStatusList',
        label: '车辆占用情况',
        type: 'picker',
        attrs: {
          options: dict.tagStatusEnums,
        },
      },
      // {
      //   prop: 'tboxEquipmentStatus',
      //   label: 'TBOX设备状态',
      //   type: 'picker',
      //   show: supplierInfo.value.config?.hrhcTboxEnabled === 1,
      //   attrs: {
      //     options: dict.tboxEquipmentStatusList,
      //   },
      // },
      {
        prop: 'etcWorkStatus',
        label: 'ETC工作状态',
        type: 'picker',
        show: supplierInfo.value.config?.hrhcEtcEnabled === 1 || supplierInfo.value.config?.quantumEtcEnabled == 1,
        attrs: {
          options: dict.etcWorkStatusList,
        },
      },
      {
        prop: 'etcSource',
        label: 'ETC设备服务商',
        type: 'picker',
        attrs: {
          options: dict.etcSourceEnums,
        },
      },
      {
        prop: 'nextMaintenanceMileage',
        label: '距离下次保养里程小于等于',
        type: 'input-number',
      },
      {
        prop: ['compulsoryEndDateStart', 'compulsoryEndDateEnd'],
        label: '交强险到期日',
        type: 'daterange-picker',
        attrs: {
          mode: 'date',
          valueFormat: 'YYYY-MM-DD',
        },
      },
      {
        prop: ['businessEndDateStart', 'businessEndDateEnd'],
        label: '商业险到期日',
        type: 'daterange-picker',
        attrs: {
          mode: 'date',
          valueFormat: 'YYYY-MM-DD',
        },
      },
      {
        prop: ['planTimeStart', 'planTimeEnd'],
        label: '年检到期日',
        type: 'daterange-picker',
        attrs: {
          mode: 'date',
          valueFormat: 'YYYY-MM-DD',
        },
      },
    ]
  })

  const supplierInfo = ref<any>({})

  // 获取商户信息
  const getSupplierInfo = () => {
    getEnterpriseDetail().then((res: any) => {
      const result = res.result
      supplierInfo.value = result
    })
  }

  const searchBarSearch = (val: any) => {
    queryParam.value = {
      ...queryParam.value,
      keyword: val,
    }
    resetRefresh()
  }

  const onFilterNavbarConfirm = (params: any) => {
    const tagStatusList = Array.isArray(params.tagStatusList) ? params.tagStatusList : [params.tagStatusList]
    queryParam.value = {
      ...queryParam.value,
      ...params,
      tagStatusList: params.tagStatusList ? tagStatusList : undefined,
    }
    resetRefresh()
  }

  const navigatorAdd = () => uni.navigateTo({ url: '/pages/asset/car-manager/form/index' })

  const tabsChange = (index: any, val: any) => {
    queryParam.value = {
      ...queryParam.value,
      operateStatus: val.value,
    }
    resetRefresh()
  }

  uni.$on('getList', function () {
    queryParam.value.pageNumber = 1
    dataSource.value = []
    loadData()
  })

  const activedTab = ref(0)
  onLoad((options = {}) => {
    queryParam.value.operateStatus = options.operateStatus
    if (options.siteId) {
      queryParam.value.siteId = options.siteId
      queryParam.value.siteName = options.siteName
    }
    if (options.operateStatus == 10) {
      activedTab.value = 1
    } else if (options.operateStatus == 20) {
      activedTab.value = 2
    } else if (options.operateStatus == 30) {
      activedTab.value = 3
    } else if (options.operateStatus == 60) {
      activedTab.value = 4
    }
    loadData()
    getSupplierInfo()
  })

  onUnload(() => {
    uni.$off('repliceVisibleFn')
    uni.$off('disposeVisibleFn')
    uni.$off('getList')
  })
</script>

<style lang="less" scoped>
  .container {
    height: 100vh;
    background-color: rgba(247, 248, 250, 1);
  }
  .record-list {
    padding: 24rpx 24rpx;
  }
  .manager-search {
    position: sticky;
    top: 44px;
    // z-index: 999;
  }
  .ve-bottom-box {
    height: 132rpx;
  }
</style>
